package com.feilx.changggou.seckill.common;

import com.changgou.utils.DateUtil;
import com.changgou.utils.RedisUtils;
import com.feilx.changggou.seckill.entity.TbSeckillEntity;
import com.feilx.changggou.seckill.service.TbSeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Component
public class LoadSeckillToRedis {

    @Autowired
    private RedisUtils redisUtils;

    public static  final String REDIS_KILL_KEY = "SECKILL_KEY_";

    public static  final  String REDIS_STOCK_COUNT  = "REDIS_STOCK_COUNT_";

    @Autowired
    private TbSeckillService tbSeckillService;

    @Scheduled(cron = "0/5 * * * * ?")
    public void load(){
        // 获取产品时间菜单
        List<Date> dateMenus = DateUtil.getDateMenus();

        dateMenus.stream().forEach( date -> {
            String timespace = DateUtil.data2str(date, "yyyyMMddHH");

            Set<String> hkeys = redisUtils.hkeys(REDIS_KILL_KEY + timespace);
            // 获取秒杀商品
            List<TbSeckillEntity> goods = tbSeckillService.querySeckill(date,hkeys);
            // 秒杀商品压入redis数据库
            goods.stream().forEach( good->{
                redisUtils.hset(REDIS_KILL_KEY+timespace,String.valueOf(good.getId()),good,60*60*2);
                System.out.println(good);
                // 设置商品库存
                redisUtils.set(REDIS_STOCK_COUNT+good.getId(),good.getStockCount());
            });

        });

    }

    // 加载秒杀商品库存
    //@Scheduled(cron = "0/5 * * * * ?")
    public void loadSecillGoodsCount(){

    }
}
